package com.yy.servlet;

import com.yy.db.UserDBUtil;
import com.yy.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name="LoginServlet",value="/login" )
public class LoginServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        System.out.println("初始化servlet会执行一次");
    }

    @Override
    public void destroy() {
        System.out.println("销毁当前实例时执行一次");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doGet 被调用===============");
        //获取到页面传输过来的用户名和密码
        String name =req.getParameter("name");
        String pwd =req.getParameter("pwd");
        System.out.println("name = " + name);
        System.out.println("pwd = " + pwd);
        UserDBUtil userDBUtil =new UserDBUtil();
        User user = userDBUtil.login(name, pwd);
        System.out.println(user);
        if(user ==null){
            req.getSession().setAttribute("msg","用户名或者密码错误");
            resp.sendRedirect("/login.jsp");
        }else{
            req.getSession().setAttribute("user",user);
            resp.sendRedirect("/index.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
